﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using static System.Net.Mime.MediaTypeNames;

namespace Petroleum.Tool
{
    public static class StreamChuLi
    {
        /// <summary>
        /// 将byte数组转换为文件并保存到指定地址
        /// </summary>
        /// <param name="buff">byte数组</param>
        /// <param name="savepath">保存地址</param>
        public static void Bytes2File(byte[] buff, string savepath)
        {
            if (System.IO.File.Exists(savepath))
            {
                System.IO.File.Delete(savepath);
            }

            FileStream fs = new FileStream(savepath, FileMode.CreateNew);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(buff, 0, buff.Length);
            bw.Close();
            fs.Close();
        }

        public static byte[] StreamToBytes(Stream stream)

        {

            byte[] bytes = new byte[stream.Length];

            stream.Read(bytes, 0, bytes.Length);

            // 设置当前流的位置为流的开始 

            stream.Seek(0, SeekOrigin.Begin);

            return bytes;

        }

        /// 将 byte[] 转成 Stream

        public static Stream BytesToStream(byte[] bytes)

        {

            Stream stream = new MemoryStream(bytes);

            return stream;

        }
        public static void StreamToFile(Stream stream, string fileName)

        {

            // 把 Stream 转换成 byte[] 

            byte[] bytes = new byte[stream.Length];

            stream.Read(bytes, 0, bytes.Length);

            // 设置当前流的位置为流的开始 

            stream.Seek(0, SeekOrigin.Begin);

            // 把 byte[] 写入文件 

            FileStream fs = new FileStream(fileName, FileMode.Create);

            BinaryWriter bw = new BinaryWriter(fs);

            bw.Write(bytes);

            bw.Close();

            fs.Close();

        }
        public static void DeleteDir(string file)
        {
            try
            {
                //去除文件夹和子文件的只读属性
                //去除文件夹的只读属性
                System.IO.DirectoryInfo fileInfo = new DirectoryInfo(file);
                fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;

                //去除文件的只读属性
                System.IO.File.SetAttributes(file, System.IO.FileAttributes.Normal);

                //判断文件夹是否还存在
                if (Directory.Exists(file))
                {
                    foreach (string f in Directory.GetFileSystemEntries(file))
                    {
                        if (File.Exists(f))
                        {
                            //如果有子文件删除文件
                            File.Delete(f);
                            Console.WriteLine(f);
                        }
                        else
                        {
                            //循环递归删除子文件夹
                            DeleteDir(f);
                        }
                    }
                    //删除空文件夹
                    //Directory.Delete(file);
                    //Console.WriteLine(file);
                }
            }
            catch (Exception ex) // 异常处理
            {
                Console.WriteLine(ex.Message.ToString());// 异常信息
            }
        }


        //// byte[] outputb = Convert.FromBase64String(pdfStream);
        //// StreamChuLi liuchuli = new StreamChuLi();
        //// liuchuli.StreamToFile(outputb, csm.栏目布局.管理中心.toubaodanUrl, pdfName);
        //// liuchuli.newProcess(liuchuli.toubaodanUrl, pdfName, true);

        //[DllImport("kernel32.dll")]
        //private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
        //[DllImport("kernel32.dll")]
        //private static extern bool CloseHandle(IntPtr hObject);
        //private const int OF_READWRITE = 2;
        //private const int OF_SHARE_DENY_NONE = 0x40;
        //private readonly IntPtr HFILE_ERROR = new IntPtr(-1);

        ///// <summary>
        ///// 把二维数组变成流
        ///// </summary>
        ///// <param name="bytes"></param>
        ///// <returns></returns>
        //public Stream BytesToStream(byte[] bytes)
        //{
        //    Stream stream = new MemoryStream(bytes);

        //    return stream;
        //}

        //public string toubaodanUrl = Application.StartupPath + @"\存放pdf文件\";
        //private Process E;
        ///// <summary>
        ///// 打开pdf文件
        ///// </summary>
        ///// <param name="pdfName">文件名称和地址</param>
        ///// <param name="isNowClose">是否需要调用关闭转圈圈</param>
        //public void newProcess(string url, string pdfName, bool isNowClose)
        //{
        //    try
        //    {
        //        E.Kill();
        //    }
        //    catch (Exception)
        //    {
        //    }
        //    Process T = Process.Start(url + pdfName);
        //    T.WaitForInputIdle(2000);//等2秒钟
        //    E = Process.GetProcessById(T.Id);

        //}


        ////public void killAllProcess() // 杀掉所有winword.exe进程
        ////{
        ////    System.Diagnostics.Process[] myPs;
        ////    myPs = System.Diagnostics.Process.GetProcesses();
        ////    foreach (System.Diagnostics.Process p in myPs)
        ////    {
        ////        if (p.Id != 0)
        ////        {
        ////            try
        ////            {
        ////                if (p.Modules != null)
        ////                    if (p.Modules.Count > 0)
        ////                    {
        ////                        System.Diagnostics.ProcessModule pm = p.Modules[0];
        ////                        string sdsd = p.MainWindowTitle;
        ////                        if (pm.ModuleName == "Acrobat.exe" || pm.ModuleName == "AcroRd32.exe")
        ////                        {
        ////                            p.Kill();
        ////                            Thread.Sleep(5000);
        ////                            return;
        ////                        }

        ////                    }
        ////            }
        ////            catch { }
        ////        }
        ////    }
        ////}



        ///// <summary>
        ///// 把流变成byte[]然后写入文件
        ///// </summary>
        ///// <param name="stream"></param>
        ///// <param name="fileName"></param>
        //public void StreamToFile(byte[] bt, string path1, string fileName)
        //{
        //    //杀pdf进程
        //    killAllProcess();
        //    string path = path1;
        //    if (!Directory.Exists(path))
        //    {
        //        Directory.CreateDirectory(path);
        //    }

        //    //if (VerifyFileIsOpen(fileName) == 1)
        //    //{
        //    //    stopNamedProcess(fileName);
        //    //}

        //    fileName = path1 + fileName;


        //    Stream stream = BytesToStream(bt);
        //    // 把 Stream 转换成 byte[] 
        //    byte[] bytes = new byte[stream.Length];
        //    stream.Read(bytes, 0, bytes.Length);
        //    // 设置当前流的位置为流的开始 
        //    stream.Seek(0, SeekOrigin.Begin);

        //    // 把 byte[] 写入文件 
        //    //using (FileStream fs = new FileStream(fileName, FileMode.Create))
        //    //{
        //    //    using (BinaryWriter bw = new BinaryWriter(fs))
        //    //    {

        //    //    }
        //    //}

        //    FileStream fs = new FileStream(fileName, FileMode.Create);
        //    BinaryWriter bw = new BinaryWriter(fs);
        //    bw.Write(bytes);
        //    fs.Flush();
        //    bw.Flush();
        //    bw.Close();
        //    fs.Close();
        //    bw.Dispose();
        //    fs.Dispose();

        //}

        ///// <summary>   
        ///// 检查文件是否已经打开   
        ///// </summary>   
        //private bool checkFileIsOpen(string filePath)
        //{
        //    bool flag = false;
        //    try
        //    {
        //        FileStream fs = new FileStream(filePath, FileMode.Create);
        //    }
        //    catch (Exception)
        //    {
        //        flag = true;
        //    }
        //    return flag;
        //}



        ///// <summary>   
        ///// 检查文件是否已经打开   
        ///// </summary>   
        ///// <param name="strfilepath">要检查的文件路径</param>          
        ///// <returns>-1文件不存在,1文件已经打开,0文件可用未打开</returns>   
        //private int VerifyFileIsOpen(string strfilepath)
        //{
        //    string vFileName = strfilepath;

        //    // 先检查文件是否存在,如果不存在那就不检查了   
        //    if (!File.Exists(vFileName))
        //    {
        //        return -1;
        //    }

        //    // 打开指定文件看看情况   
        //    IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE);
        //    if (vHandle == HFILE_ERROR)
        //    { // 文件已经被打开                   
        //        return 1;
        //    }
        //    CloseHandle(vHandle);

        //    // 说明文件没被打开，并且可用  

        //    return 0;
        //}

        ////C#关闭指定名字进程的方法。
        //private void stopNamedProcess(string name)
        //{
        //    foreach (Process p in System.Diagnostics.Process.GetProcessesByName(name))
        //    {
        //        try
        //        {
        //            p.Kill();
        //            p.WaitForExit();
        //        }
        //        catch (Exception exp)
        //        {
        //            System.Diagnostics.EventLog.WriteEntry("AlchemySearch:KillProcess", exp.Message, System.Diagnostics.EventLogEntryType.Error);
        //        }
        //    }
        //}
    }
}
